package com.pipi.biyesheji.service.impl;


import com.pipi.biyesheji.dao.manager.RolePermissionManager;
import com.pipi.biyesheji.dao.model.RolePermissionDO;
import com.pipi.biyesheji.dao.query.RolePermissionQuery;
import com.pipi.biyesheji.pojo.Role;
import com.pipi.biyesheji.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author pipi
 */
@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private RolePermissionManager rolePermissionManager;

    @Override
    public void setPermissions(Role role, long[] permissionIds) {
        //删除当前角色所有的权限
        RolePermissionQuery rolePermissionQuery = new RolePermissionQuery();
        rolePermissionQuery.createCriteria().andRidEqualTo(role.getId());
        List<RolePermissionDO> rolePermissionDOS = rolePermissionManager.selectByQuery(rolePermissionQuery);

        for (RolePermissionDO rolePermissionDO : rolePermissionDOS) {
            rolePermissionManager.deleteByPrimaryKey(rolePermissionDO.getId());
        }

        //设置新的权限关系
        if(null!=permissionIds) {
            for (long pid : permissionIds) {
                RolePermissionDO rolePermissionDO = new RolePermissionDO();
                rolePermissionDO.setPid(pid);
                rolePermissionDO.setRid(role.getId());
                rolePermissionManager.insertSelective(rolePermissionDO);
            }
        }
    }

    @Override
    public void deleteByRole(long roleId) {
        RolePermissionQuery rolePermissionQuery = new RolePermissionQuery();
        rolePermissionQuery.createCriteria().andRidEqualTo(roleId);
        List<RolePermissionDO> rolePermissionDOS = rolePermissionManager.selectByQuery(rolePermissionQuery);

        for (RolePermissionDO rolePermissionDO : rolePermissionDOS) {
            rolePermissionManager.deleteByPrimaryKey(rolePermissionDO.getId());
        }
    }

    @Override
    public void deleteByPermission(long permissionId) {
        RolePermissionQuery rolePermissionQuery = new RolePermissionQuery();
        rolePermissionQuery.createCriteria().andPidEqualTo(permissionId);
        List<RolePermissionDO> rolePermissionDOS = rolePermissionManager.selectByQuery(rolePermissionQuery);

        for (RolePermissionDO rolePermissionDO : rolePermissionDOS) {
            rolePermissionManager.deleteByPrimaryKey(rolePermissionDO.getId());
        }
    }
}
